package com.ermao.mymes.handler.receiver;

import com.ermao.mymes.handler.utils.GroupIdMappingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author Ermao
 * Date: 2022/5/8 14:43
 */
@Service
public class ReceiverStart {
	@Autowired
	private ApplicationContext context;

	/**
	 * receiver的消费方法常量
	 */
	private static final String RECEIVER_METHOD_NAME = "Receiver.consumer";

	/**
	 * 获取得到所有的groupId
	 */
	private static List<String> groupIds = GroupIdMappingUtils.getAllGroupIds();

	/**
	 * 下标(用于迭代groupIds位置)
	 */
	private static Integer index = 0;

	/**
	 * 为每个渠道不同的消息类型 都创建一个 Receiver 对象
	 * Receiver 的总数为 渠道数 * 消息类型
	 */
	@PostConstruct
	public void init() {
		for (int i = 0; i < groupIds.size(); i++) {
			context.getBean(Receiver.class);
		}
	}

	/**
	 * TODO 理解 这里是怎么做到替换 Receiver 前面的注解的
	 * 给每个 Receiver 对象的 consumer方法 @KafkaListener 赋值相应的 groupId
	 */
	@Bean
	public static KafkaListenerAnnotationBeanPostProcessor.AnnotationEnhancer groupIdEnhancer() {
		return (attrs, element) -> {
			if (element instanceof Method) {
				String name = ((Method) element).getDeclaringClass().getSimpleName() + "." + ((Method) element).getName();
				if (RECEIVER_METHOD_NAME.equals(name)) {
					attrs.put("groupId", groupIds.get(index));
					index++;
				}
			}
			return attrs;
		};
	}
}
